package com.macro.admin.config.security.component;

import com.macro.admin.pojo.Menu;
import com.macro.admin.pojo.Role;
import com.macro.admin.service.MenuService;
import io.swagger.annotations.ApiModelProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.security.AuthProvider;
import java.util.Collection;
import java.util.List;

/**
 * 权限控制
 * 根据请求分析请求所需的角色
 *
 * @Author: Xiao Hai
 * @Date: 2021-04-23 16:42:01
 * @since 1.0.0
 */
@Slf4j
@Component
public class CustomFilter implements FilterInvocationSecurityMetadataSource {

    @Autowired
    private MenuService menuService;


    AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {

        String requestUrl = ((FilterInvocation) o).getRequestUrl();
        List<Menu> menus = menuService.getMenusWithRole();
        for (Menu menu : menus) {
            if (antPathMatcher.match(menu.getUrl(),requestUrl)){
                log.info("成功访问地址:"+requestUrl);
                //判断请求url与菜单角色是否匹配
                String[] str = menu.getRoles().stream().map(Role::getName).toArray(String[]::new);
                return SecurityConfig.createList(str);
            }

        }
        //没比配的url默认登录即可访问
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}
